package com.wshare.websocket;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.google.gson.Gson;
import com.wshare.entity.Account;
import com.wshare.service.interfaces.IAccountService;
import com.wshare.utility.SpringContext;

@ServerEndpoint("/ws/manageaccount")
public class ManageAccountWebSocket {
	
	private static Set<Session> clients = Collections.synchronizedSet(new HashSet<Session>());
	IAccountService accountService = SpringContext.getApplicationContext().getBean(IAccountService.class);
	
	@OnMessage
	public void handleOnMsg(String msg,Session session) throws IOException{
		ObjectMapper objectMapper =  new ObjectMapper();
		Account newAccount =  objectMapper.readValue(msg, Account.class);
		accountService.addAccount(newAccount);
		//get all list account
		List<Account> accounts = accountService.getAll();
		ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
		String json  = ow.writeValueAsString(accounts);
		synchronized (clients) {
			for(Session client:clients){
				client.getBasicRemote().sendText(json);
			}
		}
	}
	
	@OnOpen
	public void handleOnOpen(Session session) throws IOException{
		clients.add(session);
		//send data for client
		List<Account> accounts = accountService.getAll();
		ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
		String json  = ow.writeValueAsString(accounts);
		session.getBasicRemote().sendText(json);
	}
	
	@OnClose
	public void handleOnClose(Session session){
		clients.remove(session);
	}
}
